<?php
class M_Tools
{
  // param:
  // array $opts, each item as key=>val,
  static public function make_options(array $opts=null, $select=null)
  {
    if (!isset($opts) || empty($opts))
      return "";
    $str = "<option value=''>请选择</option>";
    foreach($opts as $key=>$val)
      {
	$sel = $key == $select ? 'selected' : '';
	$str .= "<option value='$key' $sel>$val</option>";
      }
    return $str;
  }

  static public function log($str, $output=null)
  {
    $fp = fopen(LOG_FILE, "a");
    $s = date("H:i:s")." ".$str."\n";
    fwrite($fp, $s);
    fclose($fp);

    $debug = $output && PRINT_LOG;
    if ($debug)
      print $s."<br/>";
  }
  static public function print_r($array, $output=null)
  {
    $debug = $output && PRINT_LOG;
    if ($debug)
      {
	print_r($array);
	print "<br/>";
      }
  }

  static public function convert_mysql_results_to_array(array $result, $key_field, $value_field=null)
  {
    M_Tools::log("key field: $key_field");
    M_Tools::log("value field: $value_field");
    if (count($result) < 1)
      return null;
    $array = array();
    foreach($result as $res)
      {
	M_Tools::print_r($res);
	$array[$res[$key_field]] = $value_field ? $res[$value_field] : $res;
      }
    
    return $array;
  }

  static public function get_all_surnames()
  {
    $array = array();
    $fp = fopen(SURNAMES, "r");
    if ($fp)
      {
	/* while($s = fgets($fp)) */
	/*   $array[$s] = 0; */
	while(list($id, $surname) = fscanf($fp, "%s %s"))
	  {
	    $array[$surname] = $id;
	  }
      }
    fclose($fp);
    
    return $array;
  }

  /**
   * @param $surname
   * @return surname id
   **/
  static public function get_surname_id($surname)
  {
    $array = M_Tools::get_all_surnames();
    return isset($array[$surname]) ? $array[$surname] : null;
  }

  static public function return_bytes($val) 
  {
    $val = trim($val);
    $last = strtolower($val[strlen($val)-1]);
    switch($last) {
      // The 'G' modifier is available since PHP 5.1.0
    case 'g':
      $val *= 1024;
    case 'm':
      $val *= 1024;
    case 'k':
      $val *= 1024;
    }

    return $val;
  }

  /* give people's a default figure while figure does not exists */
  static public function get_figure_url($figure, $gender)
  {
    if (preg_match("/^http:\/\//", $figure))
      return $figure;
    else
      return $figure && file_exists(WEB_ROOT.$figure) ? $figure : 
	($gender == MALE ? MALE_FIGURE : FEMALE_FIGURE);
  }

  static public function del_cache($sql)
  {
    $key = md5($sql);
    if (function_exists("apc_fetch") && apc_exists($key))
      apc_delete($key);
  }

  static public function create_crumbs_path($url)
  {
    $data = array(
		  array("url"=>"/", "querystring"=>"", "link"=>"1", "title"=>"家谱百科", "keywords"=>"家谱,家谱树,宗谱", "description"=>"家谱百科是一款采用最新技术的家谱应用，您可以通过电脑、手机实时查看、构建您的家谱，查看家庭成员的家谱、生平事迹、和照片展示。您可以和您家族的其他分支成员共同编纂家谱。您还可以为完善公众人物的家谱贡献力量。",
			/* array("url"=>"/index/index", "querystring"=>"", "link"=>"1", "title"=>"家谱百科", "keywords"=>"家谱,家谱树,宗谱", "description"=>"家谱百科是一款采用最新技术的家谱应用，您可以通过电脑、手机实时查看、构建您的家谱，查看家庭成员的家谱、生平事迹、和照片展示。您可以和您家族的其他分支成员共同编纂家谱。您还可以为完善公众人物的家谱贡献力量。",  */
			"children"=>array(
					  array("url"=>"/index/guide", "title"=>"常见问题", "keywords"=> "常见问题", "description"=>"常见问题"),
					  array("url"=>"/index/copyright", "title"=>"版权声明", "keywords"=> "版权声明", "description"=>"本网展的版权声明"),
					  array("url"=>"/index/links", "title"=>"友情链接", "keywords"=> "友情链接", "description"=>"友情链接"),
					  array("url"=>"/users/login", "title"=>"用户登录", "keywords"=> "用户登录", "description"=>"用户登录"),
					  array("url"=>"/users/register", "title"=>"用户注册", "keywords"=> "用户注册", "description"=>"用户注册"),
					  array(
						"url"=>"/surnames/index", "querystring"=>"", "link"=>"1", "title"=>"百家姓", "keywords"=>"百家姓,百家姓家谱图", "description"=>"在线家谱的百家姓一览",
						"children"=>array(array("url"=>"/surnames/show", "querystring"=>"surname=#surnameid#", "link"=>"1", "title"=>"#surname#氏家谱", "keywords"=>"#surname#氏家谱,#surname#姓家谱,#surname#家家谱,#surname#氏名人", "description"=>"最新#surname#氏家谱、#surname#氏人物列表，#surname#氏族谱录，#surname#氏名人资料库",
									"children"=>array(
											  array(
												"url"=>"/users/home", "querystring"=>"userid=#userid#", "link"=>"1", "title"=>"#user#的主页", "keywords"=>"#user#的主页,#user#档案,#user#生平", "description"=>"#user#的主页，包括基本信息、生平事迹、照片资料",
												"children"=>array(array("url"=>"/users/search", "querystring"=>"userid=#userid#", "link"=>"1", "title"=>"家谱搜索", "keywords"=>"#user#家谱搜索", "description"=>"搜索#user#的家谱、家人",
															"children"=>array(array("url"=>"/relation/request", "querystring"=>"", "link"=>"0", "title"=>"添加#user#的家庭成员","keywords"=>"添加#user#的家庭成员", "description"=>"添加#user#的家庭成员",
																		"children"=>array(array("url"=>"/relation/insert", "querystring"=>"", "link"=>"0", "title"=>"添加结果"))),
																	  )),
														  array("url"=>"/users/restore", "querystring"=>"", "link"=>"0", "title"=>"恢复", "keywords"=>"", "description"=>"",),
														  array(
															"url"=>"/users/contribution", "querystring"=>"userid=#userid#", "link"=>"1", "title"=>"#user#的贡献记录", "keywords"=>"#author#的贡献记录", "description"=>"#author#在家谱百科的贡献记录",
															"children"=>array(),
															),
														  array("url"=>"/tree/index", "querystring"=>"userid=#userid#", "link"=>"1", "title"=>"#user#家谱", "keywords"=>"#user#家谱,#user#家谱树,#user#在线家谱", "description"=>"#user#的在线家谱, #user#的世系图，#user#的家谱树"),
														  array("url"=>"/users/album", "querystring"=>"userid=#userid#", "link"=>"1", "title"=>"#user#相册", "keywords"=>"#user#相册,#user#图片展", "description"=>"#user#的相册, #user#的图集，#user#照片展"),
														  array("url"=>"/users/edit_entry", "querystring"=>"userid=#userid#", "link"=>"1", "title"=>"编辑", "keywords"=>"", "description"=>"",
															"children"=>array(
																	  array("url"=>"/users/ask_delete", "querystring"=>"", "link"=>"0", "title"=>"删除", "keywords"=>"", "description"=>"",
																		"children"=>array(array("url"=>"/users/delete", "querystring"=>"", "link"=>"0", "title"=>"删除成功", "keywords"=>"", "description"=>""))),
																	  array("url"=>"/users/edit", "querystring"=>"userid=#userid#", "link"=>"1", "title"=>"基本信息", "keywords"=>"", "description"=>"",
																		"children"=>array(array("url"=>"/users/baseinfo_history", "querystring"=>"userid=#userid#", "link"=>"1", "title"=>"历史记录","keywords"=>"", "description"=>"", 
																					"children"=>array(array("url"=>"/users/baseinfo_restore", "querystring"=>"", "link"=>"0", "title"=>"恢复", "keywords"=>"", "description"=>""))),
																				  array("url"=>"/users/update", "querystring"=>"", "link"=>"0", "title"=>"更新成功", "keywords"=>"", "description"=>""))),

																	  array("url"=>"/relation/show", "querystring"=>"userid=#userid#", "link"=>"1", "title"=>"家庭成员", "keywords"=>"", "description"=>"",
																		"children"=>array(array("url"=>"/relation/add", "querystring"=>"userid=#userid#", "link"=>"1", "title"=>"添加成员","keywords"=>"", "description"=>"",
																					"children"=>array(array("url"=>"/relation/add_possible_relation", "querystring"=>"", "link"=>"0", "title"=>"成功", "keywords"=>"", "description"=>""),)),									  
																				  array("url"=>"/relation/delete_complete", "querystring"=>"", "link"=>"0", "title"=>"删除成功", "keywords"=>"", "description"=>""),
																				  array("url"=>"/relation/history", "querystring"=>"", "link"=>"0", "title"=>"历史记录","keywords"=>"", "description"=>"",
																					"children"=>array(array("url"=>"/relation/relation_restore_complete", "querystring"=>"", "link"=>"0", "title"=>"恢复成功", "keywords"=>"", "description"=>""))))),

																	  array("url"=>"/users/show_events", "querystring"=>"userid=#userid#", "link"=>"1", "title"=>"生平事迹","keywords"=>"", "description"=>"",
																		"children"=>array(array("url"=>"/users/add_event", "querystring"=>"userid=#userid#", "link"=>"1", "title"=>"添加事件","keywords"=>"", "description"=>"",
																					"children"=>array(array("url"=>"/users/insert_event_complete", "querystring"=>"userid=#userid#", "link"=>"1", "title"=>"更新成功", "keywords"=>"", "description"=>""))),
																				  array("url"=>"/users/edit_event", "querystring"=>"", "link"=>"0", "title"=>"编辑事件","keywords"=>"", "description"=>"",
																					"children"=>array(array("url"=>"/users/update_event_complete", "querystring"=>"", "link"=>"0", "title"=>"更新成功", "keywords"=>"", "description"=>""))),
																				  array("url"=>"/users/delete_event_complete", "querystring"=>"", "link"=>"0", "title"=>"删除", "keywords"=>"", "description"=>""),
																				  array("url"=>"/users/event_history", "querystring"=>"", "link"=>"0", "title"=>"历史记录","keywords"=>"", "description"=>"",
																					"children"=>array(array("url"=>"/users/event_restore_complete", "querystring"=>"", "link"=>"0", "title"=>"恢复成功", "keywords"=>"", "description"=>""))))),
																	  array("url"=>"/users/edit_album", "querystring"=>"userid=#userid#", "link"=>"1", "title"=>"相册","keywords"=>"", "description"=>"",
																		"children"=>array(array("url"=>"/users/edit_photo", "querystring"=>"", "link"=>"0", "title"=>"编辑","keywords"=>"", "description"=>"",
																					"children"=>array(array("url"=>"/users/update_photo_complete", "querystring"=>"", "link"=>"0", "title"=>"编辑成功", "keywords"=>"", "description"=>""))),
																				  array("url"=>"/users/photo_delete_complete", "querystring"=>"", "link"=>"0", "title"=>"删除", "keywords"=>"", "description"=>""),
																				  array("url"=>"/users/add_photo", "querystring"=>"", "link"=>"0", "title"=>"添加照片","keywords"=>"", "description"=>"",
																					"children"=>array(array("url"=>"/users/insert_photo_complete", "querystring"=>"", "link"=>"0", "title"=>"添加成功", "keywords"=>"", "description"=>""))),
																				  array("url"=>"/users/photo_history", "querystring"=>"", "link"=>"0", "title"=>"历史记录","keywords"=>"", "description"=>"",
																					"children"=>array(array("url"=>"/users/photo_restore_complete", "querystring"=>"", "link"=>"0", "title"=>"照片恢复成功", "keywords"=>"", "description"=>""))))),
																	  array("url"=>"/users/add_figure", "querystring"=>"userid=#userid#", "link"=>"1", "title"=>"头像","keywords"=>"", "description"=>"",
																		"children"=>array(array("url"=>"/users/edit_figure", "querystring"=>"", "link"=>"0", "title"=>"选择头像","keywords"=>"", "description"=>"",
																					"children"=>array(array("url"=>"/users/update_figure", "querystring"=>"", "link"=>"0", "title"=>"更新成功", "keywords"=>"", "description"=>""))),))
																	  )
															)
														  )
												)
											  )
									)),
						),
					  array("url"=>"/users/show_photo_wall", "querystring"=>"", "link"=>"1", "title"=>"家谱照片墙", "keywords"=>"家谱照片墙,家谱照片,家谱风采", "description"=>"展示家谱相册里面的照片"),
					  array(
						"url"=>"/family/manage", "querystring"=>"userid=#userid#", "link"=>"1", "title"=>"管理家谱", "keywords"=>"管理家谱", "description"=>"管理家谱",
						"children"=>array(array("url"=>"/family/view", "querystring"=>"", "link"=>"0", "title"=>"查看", "keywords"=>"查看家谱", "description"=>"查看家谱信息"),
								  array("url"=>"/family/edit", "querystring"=>"", "link"=>"0", "title"=>"编辑", "keywords"=>"编辑家谱", "description"=>"编辑已有家谱"),
								  array("url"=>"/family/add", "querystring"=>"userid=#userid#", "link"=>"1", "title"=>"添加", "keywords"=>"添加家谱", "description"=>"添加一个新家谱",
									"children"=>array(array("url"=>"/family/add_complete", "querystring"=>"", "link"=>"0", "title"=>"成功"))),
								  ),
						),
					  array("url"=>"/users/login", "querystring"=>"", "link"=>"0", "title"=>"登录", "keywords"=>"登录","description"=>"登录页面"),
					  )),
		  );

    $path = array();
    M_Tools::get_step($url, $data, $path);
    return $path;
  }

  static public function get_step($url,  $array, &$path)
  {
    foreach($array as $a)
      {
	$e = $a;//array("url"=>$a["url"], "title"=>$a["title"], "link"=>$a["link"]);
	unset($e["children"]);
	if ($a["url"] == $url)
	  {
	    array_push($path, $e);
	    return $path;
	  }
	else
	  {
	    if (isset($a["children"]) && count($a["children"]) > 0)
	      {
		array_push($path, $e);
		$r = M_Tools::get_step($url,  $a["children"], $path);
		if ($r)
		  return $r;
	      }
	  }
      }

    array_pop($path);
    return null;
  }

  static public function check_photo_wall()
  {
    if (!file_exists(PHOTO_WALL_PATH) || (time() - filemtime(PHOTO_WALL_PATH)) > ACTIVE_EXPIRED)
      {
	$fp = fopen(PHOTO_WALL_PATH, "w");
	fwrite($fp, file_get_contents("http://".DOMAIN."/users/photo_wall"));
	fclose($fp);
      }    
  }

  static public function check_surnames()
  {
    if (!file_exists(SURNAMES_PATH) || (time() - filemtime(SURNAMES_PATH)) > ACTIVE_EXPIRED)
      {    
	$fp = fopen(SURNAMES_PATH, "w");
	fwrite($fp, file_get_contents("http://".DOMAIN."/surnames/build"));
	fclose($fp);
      }
  }

  static public function check_hot_people()
  {
    if (!file_exists(ACTIVE_PEOPLE_PATH) || (time() - filemtime(ACTIVE_PEOPLE_PATH)) > ACTIVE_EXPIRED)
      {
	$db = new M_qin_users();
	$fp = fopen(ACTIVE_PEOPLE_PATH, "w");
	$hotfp = fopen(HOT_PEOPLE_IDS, "r");
        while($line=fgets($hotfp))
	  {
	    $person = explode(',', $line);
	    $user = $db->get($person[0]);
	    $figure = M_Tools::get_figure_url($user["figureurl"], $user["gender"]);
	    $str = '
                        <div class="figure hot-figure">
                        <a class="a-to-tree" title="'.$person[1].'" href="/tree/index?userid='.$user["id"].'"><img alt="'.$user["realname"].'" src="'.$figure.'"/></a>
                        <a class="a-to-home color2" colorattr="color" title="'.$person[1].'" href="/users/home?userid='.$user["id"].'">'.$user["realname"].'</a>
                        </div>';

	    fwrite($fp, $str);
	  }
	fclose($hotfp);
	fclose($fp);
      }
  }

  static public function check_latest_people()
  {
    if (!file_exists(LATEST_PEOPLE_PATH) || (time() - filemtime(LATEST_PEOPLE_PATH)) > ACTIVE_EXPIRED)
      {
	$fp = fopen(LATEST_PEOPLE_PATH, "w");
	fwrite($fp, file_get_contents("http://".DOMAIN."/users/get_latest"));
	fclose($fp);
      }
  }

}

